import config
import os
from utils import *


def register():
	return Admin()


class Admin:
	def __init__(self):
		self.type = 'passive'

	def run(self, gum, msg):
		if not msg['type'] in ('FriendMessage', 'GroupMessage') \
				or len(msg['messageChain']) <= 1 \
				or not msg['sender']['id'] in config.bubbles.admin.ids \
				or msg['messageChain'][1]['type'] != 'Plain':
			return
		log('糖糖收到了管理员的消息！')
		for inst in config.bubbles.admin.insts:
			getattr(self, inst)(gum, msg, msg['messageChain'][1]['text'], msg['sender']['id'])

	def reload(self, gum, msg, text, target):
		if text == '*重启':
			python = sys.executable
			os.execl(python, python, *sys.argv)
			exit(0)

	def say(self, gum, msg, text, target):
		splitted = text.split('\n')
		if splitted[0] == '*私发' and len(splitted) > 2 and splitted[1].isdigit():
			target = int(splitted[1])
			chain = MsgChain()
			for line in splitted[2:]:
				chain.addPlain(line + '\n')
			sendFriends(chain, target)

	def groupSay(self, gum, msg, text, target):
		splitted = text.split('\n')
		if splitted[0] == '*群发' and len(splitted) > 2 and splitted[1].isdigit():
			target = int(splitted[1])
			chain = MsgChain()
			for line in splitted[2:]:
				chain.addPlain(line + '\n')
			sendGroups(chain, target)

	def command(self, gum, msg, text, target):
		class Temp:
			pass
		tmp = Temp()
		splitted = text.split('\n')
		if splitted[0] == '*运行' and len(splitted) > 1:
			log('糖糖正在运行管理员的代码……')
			with trying():
				for line in splitted[1:]:
						exec(line)